#!/usr/bin/env python
# -*- coding: utf-8 -*-

from utils import log
from sqlalchemy.orm import mapper, sessionmaker
from sqlalchemy import Table, MetaData, Column, Integer, String, Unicode, UnicodeText, DateTime, TIMESTAMP, func, and_, \
    or_
from controls.data_pool_mysql import engine

metadata = MetaData()
Session = sessionmaker()
Session.configure(bind=engine)

"""user_buddy collection has
    id:                     自增id（int）
    userid:                 被关注用户id（int）
    fanuserid:              关注用户id（int）
    utime:                  更新时间（datetime）
"""

class UserBuddyItem(object):

    def to_dict(self):
        res = {}
        res['userid'] = self.userid
        res['fanuserid'] = self.fanuserid
        res['utime'] = self.utime.strftime("%Y-%m-%d %H:%M:%S")\
            if self.utime else ""

        return res

    def __repr__(self):
        return "%d" % (self.userid)


user_buddy_table = Table(
    'user_buddy', metadata,
    Column('id', Integer, primary_key=True, autoincrement=True),
    Column('userid', Integer, index=True, nullable=False),
    Column('fanuserid', Integer, index=True, nullable=False),
    Column('utime', TIMESTAMP, server_default=func.now(), onupdate=func.now())
)

mapper(UserBuddyItem, user_buddy_table)

def create_user_buddy_table_if_not_exist():
    metadata.create_all(engine)

def add_user_buddy_item(p_item):
    item = UserBuddyItem()
    item.userid = p_item['userid']
    item.fanuserid = p_item['fanuserid']
    try:
        session = Session()
        session.add(item)
        session.flush()
        session.commit()
        return True
    except Exception as e:
        log.exp(e)
        session.rollback()
        return False
    finally:
        session.close()

def update_unfollow_by_userid_isfollow(p_userid, p_fanuserid):
    try:
        session = Session()
        session.query(UserBuddyItem).filter_by(userid=p_userid, fanuserid=p_fanuserid).delete()
        session.flush()
        session.commit()
        return True
    except Exception as e:
        log.exp(e)
        session.rollback()
        return None
    finally:
        session.close()

def validate_follow_by_userid_fuserid(p_current_userid, p_userid):
    try:
        session = Session()
        isfollowed = session.query(UserBuddyItem).filter_by(userid=p_current_userid, fanuserid=p_userid).first() # 是否被关注
        isfollow = session.query(UserBuddyItem).filter_by(userid=p_userid, fanuserid=p_current_userid).first()   # 是否关注别人

        if isfollowed and isfollow:
            return 3            # 互相关注
        elif isfollow:
            return 1            # 当前登录用户关注此用户
        elif isfollowed:
            return 2            # 当前用户被此用户关注
        else:
            return 0            # 无任何关系
    except Exception as e:
        log.exp(e)
        session.rollback()
        return None
    finally:
        session.close()

def get_user_buddy_count_by_userid(p_userid):
    try:
        session = Session()
        follow = session.query(func.count(UserBuddyItem.userid)).filter_by(fanuserid=p_userid).first()
        fans = session.query(func.count(UserBuddyItem.userid)).filter_by(userid=p_userid).first()
        result = {
            'follow': follow[0] if follow else 0,
            'fans': fans[0] if fans else 0
        }
        return result
    except Exception as e:
        log.exp(e)
        session.rollback()
        return None
    finally:
        session.close()

def get_user_follow_by_userid(p_userid, p_begin, p_limit):
    try:
        session = Session()
        follow = session.query(UserBuddyItem).filter_by(fanuserid=p_userid) \
            .order_by(UserBuddyItem.utime.desc()).offset(p_begin).limit(p_limit).all()
        result = [item.to_dict()['userid'] for item in follow]
        return result
    except Exception as e:
        log.exp(e)
        session.rollback()
        return None
    finally:
        session.close()

def get_user_follow_by_userid_only(p_userid):
    try:
        session = Session()
        follow = session.query(UserBuddyItem).filter_by(fanuserid=p_userid).all()
        result = [item.to_dict()['userid'] for item in follow]
        return result
    except Exception as e:
        log.exp(e)
        session.rollback()
        return None
    finally:
        session.close()

def get_user_fans_by_userid(p_userid, p_begin, p_limit):
    try:
        session = Session()
        fans = session.query(UserBuddyItem).filter_by(userid=p_userid) \
            .order_by(UserBuddyItem.utime.desc()).offset(p_begin).limit(p_limit).all()
        result = [item.to_dict()['fanuserid'] for item in fans]
        return result
    except Exception as e:
        log.exp(e)
        session.rollback()
        return None
    finally:
        session.close()

if __name__ == "__main__":
    create_user_buddy_table_if_not_exist()